/* 高德天气 */
import { ref } from 'vue';

const weather = ref({});

// async function getCityCode() {
//   return new Promise((resolve, reject) => {

//     async function showPosition(position) {
//       const { latitude, longitude } = position.coords;
//       let url = `https://restapi.amap.com/v3/geocode/regeo?location=${longitude.toFixed(6)},${latitude.toFixed(6)}&key=2a4f12ab391e6ffcdae382f3e9196f47`;
  
//       const { infocode, regeocode } = await fetch(url).then(res => res.json())
  
//       if (infocode !== '10000') {
//         console.log('暂无天气信息');
//         resolve('');
//         // weather.value = '暂无天气信息'
//         return;
//       }
      
//       resolve(regeocode.addressComponent.adcode);
//     }
  
//     function showError(error) {
//       switch (error.code) {
//         case error.PERMISSION_DENIED:
//           console.log("User denied the request for Geolocation.");
//           break;
//         case error.POSITION_UNAVAILABLE:
//           console.log("Location information is unavailable.");
//           break;
//         case error.TIMEOUT:
//           console.log("The request to get user location timed out.");
//           break;
//         case error.UNKNOWN_ERROR:
//           console.log("An unknown error occurred.");
//           break;
//       }
//     }
  
//     console.log(navigator.geolocation);

//     if ("geolocation" in navigator) {
//       navigator.geolocation.getCurrentPosition(showPosition, showError);
//     }
//   })

// }

async function setWeather() {
  // const adcode = await getCityCode();
  //  城市编码 adcode
  const adcode = localStorage.getItem('adcode') || 321202;

  if(adcode) {
    let weatherUrl = `https://restapi.amap.com/v3/weather/weatherInfo?city=${adcode}&key=2a4f12ab391e6ffcdae382f3e9196f47`;
    const { infocode, lives } = await fetch(weatherUrl).then(res => res.json());
    if(infocode !== '10000') return;
    weather.value = lives[0];
  }
  
}

export default function useWeather(): any[] {
  return [weather, setWeather];
}
